<?php

class ApiClient
{
    private $AppId = '10037e6f803bc8ab01805fd07db4000d';   //产品ID，由银联商务方提供
    private $AppKey = '18a3a8d41b9f44d9acdf39c360f7a971';  //产品密钥，由银联商务方提供
    private $gateway = '';   //接口网关
    private $timestamp;
    private $msgSrcId = '103A';   //来源编号
    private $noticeKey = 'impARTxrQcfwmRijpDNCw6hPxaWCddKEpYxjaKXDhCaTCXJ6';  //通知回调密钥
    private $mid = '898100054115259';   //商户号

    private $tid = '00000001';      // 终端号
    private $planId = 'd2041b5c28474a2c9bb8b70128d71160';     // 协议模板id

    function __construct()
    {
        $mode = 'dev';
        $uri = 'https://' . ($mode == 'dev' ? 'test-api-open' : 'api-mop') . '.chinaums.com/';
        $this->gateway = $uri;
        $this->timestamp = date('YmdHis');
    }

    /**
     * 获取毫生秒时间缀
     * @return float
     */
    private function getMillisecond() {
        list($microsecond , $time) = explode(' ', microtime()); //' '中间是一个空格
        return (float)sprintf('%.0f',(floatval($microsecond)+floatval($time))*1000);

    }

    /**
     * 方法一：获取随机字符串
     * @param number $length 长度
     * @param string $type 类型
     * @param number $convert 转换大小写
     * @return string 随机字符串
     */
    private function random($length = 6, $type = 'all', $convert = 0)
    {
        $config = array(
            'number' => '1234567890',
            'letter' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
            'numstr' => 'abcdefghjkmnpqrstuvwxyz1234567890',
            'all' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
        );

        if (!isset($config[$type]))
            $type = 'string';
        $string = $config[$type];

        $code = '';
        $strlen = strlen($string) - 1;
        for ($i = 0; $i < $length; $i++) {
            $code .= $string[mt_rand(0, $strlen)];
        }
        if (!empty($convert)) {
            $code = ($convert > 0) ? strtoupper($code) : strtolower($code);
        }
        return $code;
    }

    /**
     * 加密方式
     * @param $str
     * @return string
     */
    private function SHA256Hex($str){
        $re=hash('sha256', $str, true);
        return bin2hex($re);
    }

    function hash256($input) {
        $hash = hash("sha256", utf8_encode($input));
        $output ="";
        foreach(str_split($hash, 2) as $key => $value) {
            if (strpos($value,"0") === 0) {
                $output .= str_replace("0","", $value);
            } else {
                $output .= $value;
            }
        }
        return $output;
    }


    private function createSignature()
    {
        $nonce = $this->random(128);
        $str = $this->AppId.$this->timestamp.$nonce.$this->AppKey;
    }
}
